package com.lagou.boot.core;

import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author xingyi
 */
@HandlesTypes(MyWebApplicationInitializer.class)
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        List<WebApplicationInitializer> initializers = new ArrayList<>();

        if (set != null) {
            for (Class<?> aClass : set) {
                if (WebApplicationInitializer.class.isAssignableFrom(aClass)) {
                    try {
                        final WebApplicationInitializer initializer = (WebApplicationInitializer) aClass.newInstance();
                        initializers.add(initializer);
                    } catch (Throwable throwable) {
                        throw new ServletException("newInstance error", throwable);
                    }
                }
            }
        }

        for (WebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
